package com.rzico.sbl.ui.mine

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.result.ActivityResultLauncher
import androidx.annotation.RequiresApi
import androidx.core.view.isVisible
import com.fondesa.kpermissions.allGranted
import com.fondesa.kpermissions.anyPermanentlyDenied
import com.fondesa.kpermissions.extension.permissionsBuilder
import com.fondesa.kpermissions.extension.send
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivitySettingLimitBinding
import com.rzico.sbl.other.userRole
import com.xinnuo.common.extend.conditionFalse
import com.xinnuo.common.extend.conditionIf
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.requestForResult
import com.xinnuo.common.helper.AppSettingHelper.goAutoStartSetting
import com.xinnuo.common.helper.AppSettingHelper.goNotificationSetting
import com.xinnuo.common.helper.AppSettingHelper.goPermissionSetting
import com.xinnuo.common.helper.AppSettingHelper.isIgnoringBatteryOptimizations
import com.xinnuo.common.helper.AppSettingHelper.requestBatteryOptimizations
import com.xinnuo.common.helper.checkPermission
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.utils.showHintDialog

class SettingLimitActivity : BaseActivity(R.layout.activity_setting_limit) {

    private val mBinding by lazy { ActivitySettingLimitBinding.bind(getRootView()) }

    private lateinit var mLaunch: ActivityResultLauncher<Intent>
    private lateinit var mLaunchPerssion: ActivityResultLauncher<Intent>

    override fun initData() {
        initTitle(title = "权限设置")

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mLaunch = requestForResult { checkBatteryStatus() }

            checkBatteryStatus()
        }

        mLaunchPerssion = requestForResult {
            mBinding
                .settingMobile.text =
                conditionIf(
                    checkPermission(Manifest.permission.READ_CALL_LOG),
                    "已开启",
                    "快速设置"
                )
        }
    }

    override fun initListener() {
        mBinding.apply {
            settingMobileLl.isVisible = userRole in "1,2,10"
            settingLocationLl.isVisible = userRole in "1,2,3,4,7,10"

            settingMobile.text =
                conditionIf(
                    checkPermission(Manifest.permission.READ_CALL_LOG),
                    "已开启",
                    "快速设置"
                )

            settingBattery.oneClick {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!isIgnoringBatteryOptimizations()) {
                        mLaunch.requestBatteryOptimizations(baseContext)
                    }
                } else showToast("系统版本过低，暂无法设置！")
            }

            settingBack.oneClick { goAutoStartSetting() }

            settingNotify.oneClick { goNotificationSetting() }

            settingLocation.oneClick { goPermissionSetting() }

            settingMobile.oneClick {
                checkPermission(Manifest.permission.READ_CALL_LOG)
                    .conditionFalse {
                        requestPermission()
                    }
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun checkBatteryStatus() {
        mBinding
            .settingBattery
            .text = conditionIf(
            isIgnoringBatteryOptimizations(),
            "已设置",
            "快速设置"
        )
    }

    /**
     * 来电监听权限
     */
    private fun requestPermission() {
        permissionsBuilder(Manifest.permission.READ_CALL_LOG)
            .build()
            .send {
                when {
                    it.allGranted() -> {
                        mBinding.settingMobile.text = "已开启"
                    }

                    it.anyPermanentlyDenied() -> showPermissionDialog()
                }
            }
    }

    /**
     * 权限禁止显示后提示操作
     */
    private fun showPermissionDialog() {
        showHintDialog(
            hint = "通话记录权限被禁止开启，请前往设置页面手动开启",
            sure = "去设置",
            cancel = "再想想",
            isForced = true,
            onSure = {
                mLaunchPerssion.launch(
                    Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                        .apply {
                            data = Uri.parse("package:$packageName")
                        }
                )
            }
        )
    }

}